<template>
	<div>
		<zh-row :gutter="8">
			<zh-col :span="12">
				<zh-tree
					ref="orgTreeRef"
					:showSearch="false"
					funcCode="org0032"
					:nodeLevel="1"
          :height="580"
					:expand-on-click-node="false"
					:queryParam="queryTreeParam"
          :disabledList="state.checkedList"
					node-key="orgId"
					:lazy="true"
					:pagging="true"
					:props="{ label: 'orgName' }"
					:resultFields="{ treeList: 'list' }"
				>
					<template v-slot:button="{ node }">
						<zh-button v-if="node.data.fictitious!=='1'&&!node.data.moreFlag" :type="node.data.disabled ? 'success' : 'primary'"  :disabled="node.data.disabled" size="small" @click="onSelectClick(node)">
            {{ node.data.disabled ? '已选择' : '选择' }}
            </zh-button>
					</template>
				</zh-tree>
			</zh-col>

			<zh-col :span="12">
				<zh-table
					ref="orgCheckTable"
					:rowConfig="{ keyField: 'orgId' }"
					:height="580"
					:title="state.rightTitle"
					:data="state.myCheckList"
					:columns="state.checkOrgColumn"
					:layouts="['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump']"
				>
					<template #header>
						<div class="card-header">
							<span>{{ state.rightTitle }}</span>
							<el-button v-if="props.mode === 'multiple'" type="danger" plain @click="delAll">全部移除</el-button>
						</div>
					</template>
					<template #operate="{ row }">
						<zh-button type="danger" size="small" @click="del(row)">移除</zh-button>
					</template>
				</zh-table>
			</zh-col>
		</zh-row>
	</div>
</template>
<script lang="ts" setup name="orgSelect">
import { ElMessage } from 'element-plus';
// ------------------接收传入参数(组件)-------------------
const props = defineProps({
	modelValue: {
		type: [String, Array],
		default: undefined,
	},
	nameValue: {
		type: [String, Array],
		default: undefined,
	},
	//模式：multiple 多选
	mode: {
		type: String,
		default() {
			return '';
		},
	},
	checkList: {
		type: Array,
		default: () => {
			return [];
		},
	},
	orgTypeList: {
		type: Array,
		default: () => {
			return [];
		},
	},
	//最大可选人数
	max: {
		type: Number,
		default: 100,
	},
	//最小选择人数
	min: {
		type: Number,
		default: 0,
	},
});
// ------------------钩子函数----------------------------
// 初始化
onMounted(() => {
	nextTick(() => {
		state.myCheckList = props.checkList.slice();
    if(state.myCheckList&&state.myCheckList.length>0){
      let list=[] as any
      state.myCheckList.forEach((item:any)=>{
        list.push(item.orgId);
      })
      state.checkedList=list;
    }
	});
});
watch(
	() => props.checkList,
	() => {
		state.myCheckList = props.checkList.slice();
    if(state.myCheckList&&state.myCheckList.length>0){
      let list=[] as any
      state.myCheckList.forEach((item:any)=>{
        list.push(item.orgId);
      })
      state.checkedList=list;
    }
	},
	{
		deep: true,
	}
);
// ------------------定义子组件--------------------------
const orgCheckTable = ref<any>({});
const orgTreeRef=ref();
// ------------------变量区------------------------------
const queryTreeParam = ref({ parentKey: '', orgTypes: props.orgTypeList });
const state = reactive({
	leftTitle: '待选择列表',
	funcCode: '',
	rightTitle: '已选择0条',
	myCheckList: props.checkList,
  checkedList:[],//已选择的组织id
	checkOrgColumn: [
		{
			field: 'operate',
			title: '操作',
			fixed: 'left',
			align: 'center',
			width: 100,
			slots: {
				// 使用插槽模板渲染
				default: 'operate',
			},
		},
		{ field: 'orgId', title: '组织id', visible: false, fixmyCheckListed: 'left', align: 'center', width: 150 },
		{ field: 'orgName', title: '组织名称', align: 'center', fixed: 'left', minWidth: 200 },
	],
});
// ------------------方法区------------------------------

const emit = defineEmits(['update:modelValue', 'update:nameValue', 'change']);
const onSelectClick = (row: any) => {
	let list = state.myCheckList;
	if (list && list.length > 0) {
		if (list.length > props.max) {
			ElMessage.warning('已达选择上限，选择组织不能大于' + props.max + '个');
			return;
		}
		if (props.mode === 'multiple') {
			let hasList = list.filter((item: any) => item.orgId === row.orgId);
			if (hasList && hasList.length > 0) {
				ElMessage.warning('该组织已选择');
			} else {
				list.push(row);
        row.data.disabled = true;
			}
		} else {
			ElMessage.warning('只可选择一条');
		}
	} else {
		list.push(row.data);
    row.data.disabled = true;
	}
	state.rightTitle = '已选择' + list.length + '条';
	state.myCheckList = list;
};

const del = (row) => {
	let list = state.myCheckList;
	if (list && list.length > 0) {
		let hasList = list.filter((item: any) => item.orgId !== row.orgId);
		state.rightTitle = '已选择' + hasList.length + '条';
		state.myCheckList = hasList;
	}
  let node=orgTreeRef.value.getNode(row.orgId);
  node.data.disabled=false
};

const delAll = () => {
	state.myCheckList = [];
};
const success = () => {
	emit('change', state.myCheckList);
};
defineExpose({
	...toRefs(state),
	success,
});
</script>
<style lang="scss" scoped>
.search-text-color {
	color: var(--el-color-primary);
}
.card-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
}
</style>
